package cn.ffcs.uec.view.component;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.web.servlet.Servlets;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.uec.staff.manager.UecAssManager;
import cn.ffcs.uec.staff.manager.UecDocEduManager;
import cn.ffcs.uec.staff.manager.UecEncManager;
import cn.ffcs.uec.staff.manager.UecNationdutyManager;
import cn.ffcs.uec.staff.manager.UecTalentTeamManager;
import cn.ffcs.uec.staff.manager.UecTitleManager;
import cn.ffcs.uec.staff.manager.UecWorkManager;
import cn.ffcs.uec.staff.model.UecAss;
import cn.ffcs.uec.staff.model.UecDocEdu;
import cn.ffcs.uec.staff.model.UecEnc;
import cn.ffcs.uec.staff.model.UecNationduty;
import cn.ffcs.uec.staff.model.UecTalentTeam;
import cn.ffcs.uec.staff.model.UecTitle;
import cn.ffcs.uec.staff.model.UecWork;
import cn.ffcs.uec.staffAndOutStaff.component.bean.StaffTotalInfoListboxExtBean;
import cn.ffcs.uec.staffAndOutStaff.manager.StaffAndOutStaffManager;
import cn.ffcs.uec.staffAndOutStaff.vo.StaffAndOutStaff;
import cn.ffcs.uec.staffAndOutStaff.vo.StaffTotalInfo;
import cn.ffcs.uec.view.component.bean.UecStaffAllListboxExtBean;
import cn.ffcs.uec.view.manager.LogDownManager;
import cn.ffcs.uec.view.manager.UecStaffAllManager;
import cn.ffcs.uec.view.model.LogDown;
import cn.ffcs.uec.view.model.UecArticle;
import cn.ffcs.uec.view.model.UecImportantWork;
import cn.ffcs.uec.view.model.UecInnovation;
import cn.ffcs.uec.view.model.UecStaffAll;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ExportExcelNew;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.PageInfo;
import lombok.Getter;
import lombok.Setter;

/**
 * 人员推荐信息汇总表
 * 
 * @Title:
 * @Description:
 * @author BMP
 * @版权 FFCS（C） 2017
 * @date 2019年9月10日
 */
@Controller
@Scope("prototype")
public class UecStaffAllListboxExt extends Div implements IdSpace {

    private static final long serialVersionUID = -885448835759987759L;

    private static final String STAFF_AND_OUTSTAFF_ZUL = "/pages_nmg/views/uecstaffall/uecStaffAll_listbox_ext.zul";

    private UecStaffAllListboxExtBean bean = new UecStaffAllListboxExtBean();

    private UecStaffAll uecStaffAll = new UecStaffAll();

    private LogDownManager logDownManager = (LogDownManager) ApplicationContextUtil
            .getBean("logDownManager");

    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    //为了区分申报专业，形成报表（技术类、营销类、综合类）
    private String type="";
    
    
    
    
    /**
     *用于人工数据同步
     */
    
	//方便人员转换
	private StaffAndOutStaff staffAndOutStaff = new StaffAndOutStaff();

	private UecStaffAllManager uecStaffAllManager = (UecStaffAllManager) ApplicationContextUtil
			.getBean("uecStaffAllManager");
	private UecAssManager uecAssManager = (UecAssManager) ApplicationContextUtil
			.getBean("uecAssManager");
	private UecWorkManager uecWorkManager = (UecWorkManager) ApplicationContextUtil
			.getBean("uecWorkManager");
	private UecEncManager uecEncManager = (UecEncManager) ApplicationContextUtil
			.getBean("uecEncManager");
	private UecDocEduManager uecEduManager = (UecDocEduManager) ApplicationContextUtil
			.getBean("uecDocEduManager");
	//专业技术职务
	private UecTitleManager uecTitleManager = (UecTitleManager) ApplicationContextUtil
			.getBean("uecTitleManager");
	//专家人才
	private UecTalentTeamManager uecTalentTeamManager = (UecTalentTeamManager) ApplicationContextUtil
			.getBean("uecTalentTeamManager");
	//职业资格
	private UecNationdutyManager uecNationDutyManager = (UecNationdutyManager) ApplicationContextUtil
			.getBean("uecNationdutyManager");
	List logDOwnList=null;
	//人工同步数据结束

    @Getter
    @Setter
    private IPortletInfoProvider portletInfoProvider;

    public UecStaffAllListboxExt() {
        Executions.createComponents(STAFF_AND_OUTSTAFF_ZUL, this, null);
        Components.wireVariables(this, bean);
        Components.addForwards(this, this, '$');
    }

    /**
     * 界面初始化
     */
    public void onCreate() {
    	onQueryStaffTotalInfo();
    }

    /**
     * 查询员工信息
     * 
     * @throws Exception
     *             异常
     */
    public void onQueryStaffTotalInfo() {
        int activePage = bean.getUecStaffAllListboxPaging().getActivePage();
        int pageSize = bean.getUecStaffAllListboxPaging().getPageSize();
        PageInfo pageInfo = logDownManager.queryPageInfoByUecStaffAll(uecStaffAll,type, activePage + 1,
                pageSize);
        // 总条数
        if(pageInfo !=null ) {
	        bean.getTotalSize().setValue(String.valueOf(pageInfo.getTotalCount()));
	        ListModel list = new BindingListModelList(pageInfo.getDataList(), true);
	        logDOwnList=pageInfo.getDataList();
	        //logDOwnList=logDownManager.getLogDownListAll(uecStaffAll, type);
	        this.bean.getUecStaffAllListboxs().setModel(list);
	        this.bean.getUecStaffAllListboxPaging().setTotalSize(pageInfo.getTotalCount());
        }
    }

    /**
     * 每页显示事件
     */
    public void onPageSizeSelect() {
        if (this.bean.getPageListbox() != null && this.bean.getPageListbox().getSelectedItem().getValue() != null) {
            this.bean.getUecStaffAllListboxPaging().setActivePage(0);
            this.bean.getUecStaffAllListboxPaging()
                    .setPageSize(Integer.parseInt(this.bean.getPageListbox().getSelectedItem().getValue().toString()));
        }
        this.onQueryStaffTotalInfo();
    }

    /**
     * 翻页
     */
    public void onStaffTotalInfoListboxPaging() {
        onQueryStaffTotalInfo();
    }
    
    /**
     * 查询按钮
     * @throws Exception
     * @throws InterruptedException
     */
    public void onReportParametr() throws Exception, InterruptedException {
    	uecStaffAll = new UecStaffAll();
    	uecStaffAll.setCode(!StrUtil.isNullOrEmpty(bean.getStaffCode().getValue())?bean.getStaffCode().getValue():""); 
        uecStaffAll.setName(!StrUtil.isNullOrEmpty(bean.getStaffName().getValue())?bean.getStaffName().getValue():"");
        this.onQueryStaffTotalInfo();
    }

    /**
     * 清单下载按钮
     * 
     * @throws Exception
     */
    public void onDownloadlist() throws Exception {
    	
    	  PageInfo pageInfo = logDownManager.queryPageInfoByUecStaffAll(uecStaffAll, type, 1,
                  20);
    	  if(pageInfo==null || pageInfo.getDataList().size()<=0) {
    		  Messagebox.show("清单数据为空");
    		  return;
    	  }
    	  // 清单数据
        data = logDownManager.getLogDownList(uecStaffAll,type);
        if (data !=null && data.size() != 0) {
            // 设置字符集
            String charset = "UTF-8";
            String fileName = "人员推荐汇总表_" + DateUtil.getYYYYMMDD(new Date());
            HttpServletRequest httpRequest = (HttpServletRequest) Executions.getCurrent().getNativeRequest();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ExportExcelNew.exportExcel("", data, os);
            byte[] content = os.toByteArray();
            String encodedName = null;
            encodedName = URLEncoder.encode(fileName + ".xlsx", charset);
            // 将空格替换为+号
            encodedName = encodedName.replace("%20", "+");
            // 解决ie6 bug 或者是火狐浏览器
            if (encodedName.length() > 150 || Servlets.isGecko(httpRequest) || Servlets.isGecko3(httpRequest)) {
                encodedName = new String(encodedName.getBytes(charset), "ISO8859-1");
            }
            Filedownload.save(content, "application/octet-stream", encodedName);
        } else {
            Messagebox.show("数据为空!");
            return;
        }
    }

    /**
     * 重置按钮
     */
    public void onReset() {
        clearVariable();
        this.bean.getTotalSize().setValue(null);
        ListboxUtils.clearListbox(this.bean.getUecStaffAllListboxs());
        this.bean.getUecStaffAllListboxPaging().setTotalSize(1);
        uecStaffAll = new UecStaffAll();
    }

    /**
     * 清除变量
     */
    public void clearVariable() {
        uecStaffAll = null;
        data.clear();
    }
    
    
    //用于数据同步
    public void onSyschronization() throws ParseException {
    	if(logDOwnList != null && logDOwnList.size()>0) {
    		LogDown logDown = new LogDown();
    		for (int i = 0; i < logDOwnList.size(); i++) {
    			logDown=(LogDown)logDOwnList.get(i);
    			staffAndOutStaff.setPkPsndoc(logDown.getPkPsndoc());
    			updateData(logDown);
			}
    		onQueryStaffTotalInfo();
    	}
    	
    }
    
    public void updateData(LogDown logDown) throws ParseException {
    	// 考核
    			List<UecAss> findUecAssByStaffId = uecAssManager
    					.findUecAssByPkPsndoc(staffAndOutStaff);
    			// 教育
    			List<UecDocEdu> uecDocEduByUecOutStaffId = uecEduManager
    					.findUecDocEduByPkPsndoc(staffAndOutStaff);
    			String allstudy="";//全日制
    			String studyMode="1001A1100000000006B4";
    			String zaistudy="";//在职
    			String studyMode1="1001A1100000000006B9";
    			ArrayList<String> strArrayAll = new ArrayList<String> ();
    			strArrayAll.add("1001A1100000000006B4");
    			strArrayAll.add("1001A1100000000006B5");
    			strArrayAll.add("1001A1100000000006B6");
    			strArrayAll.add("1001A1100000000006B7");
    			strArrayAll.add("1001A1100000000006B8");
    			ArrayList<String> strArrayZai = new ArrayList<String> ();
    			strArrayZai.add("1001A1100000000006B9");
    			strArrayZai.add("1001A1100000000006BA");
    			strArrayZai.add("1001A1100000000006BB");
    			strArrayZai.add("1001A1100000000006BC");
    			strArrayZai.add("1001A1100000000006BD");
    			strArrayZai.add("1001A1100000000006BE");
    			strArrayZai.add("1001A1100000000006BF");
    			strArrayZai.add("1001A1100000000006BG");
    			strArrayZai.add("1001A1100000000006BH");
    			strArrayZai.add("1001A1100000000006BI");
    			if(uecDocEduByUecOutStaffId!=null) {
    				for (UecDocEdu uecdocedu:uecDocEduByUecOutStaffId) {
    				//	if(uecdocedu.getStudymode().equals(studyMode)) {
    						if(strArrayAll.contains(uecdocedu.getStudymode())) {
    						allstudy=allstudy+(!StrUtil.isNullOrEmpty(uecdocedu.getEducationName())?uecdocedu.getEducationName():"无")+"；"
    					            +(!StrUtil.isNullOrEmpty(uecdocedu.getPkDegreeName())?uecdocedu.getPkDegreeName():"无")+"\r\n"
    								+dataTraslate(uecdocedu.getBegindate())+"-"+dataTraslate(uecdocedu.getEnddate())+"；"
    					            +(!StrUtil.isNullOrEmpty(uecdocedu.getSchool())?uecdocedu.getSchool():"无")+"；"
    					            +(!StrUtil.isNullOrEmpty(uecdocedu.getMajor())?uecdocedu.getMajor():"无")+"\r\n";
    						continue;
    					//}else if(uecdocedu.getStudymode().equals(studyMode1)) {
    					}else if(strArrayZai.contains(uecdocedu.getStudymode())) {
    						zaistudy=zaistudy+(!StrUtil.isNullOrEmpty(uecdocedu.getEducationName())?uecdocedu.getEducationName():"无")+"；"
    					            +(!StrUtil.isNullOrEmpty(uecdocedu.getPkDegreeName())?uecdocedu.getPkDegreeName():"无")+"\r\n"
    								+dataTraslate(uecdocedu.getBegindate())+"-"+dataTraslate(uecdocedu.getEnddate())+"；"
    					            +(!StrUtil.isNullOrEmpty(uecdocedu.getSchool())?uecdocedu.getSchool():"无")+"；"
    					            +(!StrUtil.isNullOrEmpty(uecdocedu.getMajor())?uecdocedu.getMajor():"无")+"\r\n";
    						continue;
    						
    					}
    				}
    				allstudy=!StrUtil.isNullOrEmpty(allstudy)?allstudy:"无";
    				zaistudy=!StrUtil.isNullOrEmpty(zaistudy)?zaistudy:"无";
    			}else {
    				allstudy="无";
    				zaistudy="无";
    			}
    			logDown.setZaistudy(zaistudy);
    			logDown.setAllstudy(allstudy);
    			// 专业技术职务
    			List<UecTitle> uecTitleByUecOutStaffId=
    			uecTitleManager.getUecTitleListByPkpsndoc(staffAndOutStaff);
    			String uecTitleString="";
    			if(uecTitleByUecOutStaffId!=null) {
    				for(UecTitle ut:uecTitleByUecOutStaffId) {
    					if(uecTitleByUecOutStaffId.size()==1 &&("".equals(ut.getPkTechposttitleName())||"无专业技术职务名称".equals(ut.getPkTechposttitleName()))) {
    					   uecTitleString="无";
    					   break;
    					}else if("".equals(ut.getPkTechposttitleName())||"无专业技术职务名称".equals(ut.getPkTechposttitleName())){
    						
    						continue;
    						
    					}else {
    						uecTitleString=uecTitleString+(!StrUtil.isNullOrEmpty(ut.getGlbdef4())?(dataTraslate(ut.getGlbdef4())):"")+"获得"+"    "+ut.getTitlerankName()+"     "
    					             +ut.getPkTechposttitleName()+ "    "+ "\r\n";
    					}
    				}
    			}else {
    				 uecTitleString="无";
    			}
    			logDown.setTitleinfo(uecTitleString);
    			// 专家人才
    			List<UecTalentTeam> uecTalentTeamByUecOutStaffId=
    					uecTalentTeamManager.getUecTalentTeamListByPkpsndoc(staffAndOutStaff);
    			String uecTalentTeamString="";
    			if( uecTalentTeamByUecOutStaffId!=null) {
    				for(UecTalentTeam utt:uecTalentTeamByUecOutStaffId) {
    						String a=utt.getBegindate();
    						String b=utt.getEnddate();
    						if(!StrUtil.isNullOrEmpty(a)) {
    							a=a.substring(0,4)+"."+a.substring(5,7);
    						}
    						if(!StrUtil.isNullOrEmpty(b)) {
    							b=b.substring(0,4)+"."+b.substring(5,7);
    						}
    						//utt.getGlbdef1Name();
    						utt.getGlbdef2Name();
    						//utt.getGlbdef3Name();
    						uecTalentTeamString=uecTalentTeamString+utt.getGlbdef2Name()+";"+a+" - "+b+";"+utt.getGlbdef3Name()+"\r\n";
    					}
    			}else {
    				uecTalentTeamString="无";
    			}
    			// 职业资格
    			List<UecNationduty> uecNationDutyByUecOutStaffId=
    			uecNationDutyManager.getUecNationdutyListByPkpsndoc(staffAndOutStaff);
    			String uecNationdutyString="";
    			if( uecNationDutyByUecOutStaffId!=null) {
    				for(UecNationduty un:uecNationDutyByUecOutStaffId) {
    					if(uecNationDutyByUecOutStaffId.size()==1 &&("".equals(un.getWorknameName())||"无职业资格名称".equals(un.getWorknameName()))) {
    						uecNationdutyString="无";
    					   break;
    					}else if("".equals(un.getWorknameName())||"无职业资格名称".equals(un.getWorknameName())){
    						
    						continue;
    						
    					}else {
    						String a=un.getWorkdate();
    						if(!StrUtil.isNullOrEmpty(a)) {
    							//System.out.println("a+++"+a+"++++++"+a.substring(0,4)+"---bbb-----"+a.substring(5,7));
    							a=a.substring(0,4)+"."+a.substring(5,7);
    						}
    						uecNationdutyString=uecNationdutyString+(!StrUtil.isNullOrEmpty(un.getWorklevelName())?un.getWorklevelName():"")+"     "+un.getWorknameName()+"    "+a+"\r\n";
    					}
    				}
    			}else {
    				uecNationdutyString="无";
    			}
    			
    			//履历情况
    					List<UecWork> queryPageInfoByUecStaffId = uecWorkManager
    							.findUecWorkByPkPsndoc(staffAndOutStaff);
    					String uecworkString="";
    					if( queryPageInfoByUecStaffId!=null && queryPageInfoByUecStaffId.size()>0) {
    						for(UecWork uecWork:queryPageInfoByUecStaffId) {
    								uecWork.getDataCollection();
    								uecworkString=uecworkString+(!StrUtil.isNullOrEmpty(uecWork.getWorkcorp())?uecWork.getWorkcorp():"--")+
    										    "     "+(!StrUtil.isNullOrEmpty(uecWork.getWorkdept())?uecWork.getWorkdept():"--")+"    "+(!StrUtil.isNullOrEmpty(uecWork.getWorkpost())?uecWork.getWorkpost():"--")+"\r\n";
    							}
    					}else {
    						uecworkString="无";
    					}
    					// 奖励
    					String uecEncString="";
    					List<UecEnc> findUecEncByOutStaffId = uecEncManager
    							.findUecEncByPkPsndoc(staffAndOutStaff);	
    					if(findUecEncByOutStaffId != null && findUecEncByOutStaffId.size()>0) {
    						for(UecEnc uecEnc:findUecEncByOutStaffId) {
    							uecEncString=uecEncString+(!StrUtil.isNullOrEmpty(uecEnc.getDataCollection())?uecEnc.getDataCollection():"--")+"    "+
    									(!StrUtil.isNullOrEmpty(uecEnc.getGlbdef1())?uecEnc.getGlbdef1():"--")+"    "+(!StrUtil.isNullOrEmpty(uecEnc.getEncourorg())?uecEnc.getEncourorg():"--")+"    "+
    									(!StrUtil.isNullOrEmpty(uecEnc.getEncourrankName())?uecEnc.getEncourrankName():"--")+"\r\n";
    						}
    					}else {
    						uecEncString="无";
    					}
    					
    			logDown.setUecnationdutylist(uecNationdutyString);
    			logDown.setUectalentteamlist(uecTalentTeamString);
    			logDown.setUecworklist(uecworkString);
    			logDown.setUecenclist(uecEncString);
    			logDown.updateOnly();
    }
    public String dataTraslate(String data) throws ParseException {
    	SimpleDateFormat df=new SimpleDateFormat("yyyy-mm");
    	Date parse = df.parse(data);
    	String newDate = df.format(parse);
    	newDate=newDate.replace("-", ".");
    	return newDate;
    }
 public String StrTraslate(Date data) throws ParseException {
	 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
	 String newDate = df.format(data);
	 newDate=newDate.substring(0,4)+"-"+newDate.substring(5,7);
	 newDate=newDate.replace("-", ".");
	 return newDate;
 }

 /**
  * 日期格式转换   2019/2/1  -----》2019-02-01
  * @param data
  * @return
  * @throws ParseException
  */
 public String StrTraslateFormat(String data) throws ParseException {
	 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
	 Date newDate = df.parse(data);
	 data=df.format(newDate);
	 data=data.substring(0,4)+"-"+data.substring(5,7);
	 data=data.replace("-", ".");
	 return data;
 }
}
